﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using Microsoft.Phone.Controls;
using BYRBBS.Model;
using BYRBBS.Util;
using System.Diagnostics;
using System.IO.IsolatedStorage;
using System.IO;
using Microsoft.Phone.Shell;

namespace BYRForum
{
    public partial class LogInPage : PhoneApplicationPage
    {
        public LogInPage()
        {
            InitializeComponent();
            this.SetValue(SystemTray.IsVisibleProperty, !(bool)this.GetValue(SystemTray.IsVisibleProperty));
        }

        private void PhoneApplicationPage_Loaded(object sender, RoutedEventArgs e)
        {
            try
            {            
                //读取文件
                IsolatedStorageFile fileStorage = IsolatedStorageFile.GetUserStoreForApplication();
                //创建一个新的StreamReader
                StreamReader fileReader = null;
                fileReader = new StreamReader(new IsolatedStorageFileStream("userinfo.txt", FileMode.Open, fileStorage));
                //读取内容
                string check = fileReader.ReadLine();
                if (check == "Checked")
                {
                    SaveCheckBox.IsChecked = true;
                    UsernameBox.Text = fileReader.ReadLine();
                    PasswordBox.Password = fileReader.ReadLine();
                }
                fileReader.Close();
            }
            catch
            { 

            }
        }

        private void ConfirmButton_Click(object sender, RoutedEventArgs e)
        {
            if (UsernameBox.Text == "" || PasswordBox.Password == "")
            {
                MessageBox.Show("密码或用户名不能为空！");
                return;
            }
            App.MyInfo.Id = UsernameBox.Text;
            App.MyInfo.Password = PasswordBox.Password;
            Debug.WriteLine(App.MyInfo.Id + " " + App.MyInfo.Password);
            //保存用户名与密码
            IsolatedStorageFile store = IsolatedStorageFile.GetUserStoreForApplication();
            StreamWriter fileWriter = null;
            fileWriter = new StreamWriter(new IsolatedStorageFileStream("userinfo.txt", FileMode.Create, store));
            if (SaveCheckBox.IsChecked == true)
            {
                fileWriter.WriteLine("Checked");
                fileWriter.WriteLine(UsernameBox.Text);
                fileWriter.WriteLine(PasswordBox.Password);
            }
            else
            {
                fileWriter.WriteLine("UnChecked");
            }
            fileWriter.Close();

            String myRequestUrl = ByrApi.apiUrl + "/user/login" + ByrApi.Encode + ByrApi.appkey;
            RequestState state = new RequestState();
            HttpUtil.HttpGetWithParam(state, myRequestUrl, HttpWebRequset_LogIn_Callback);//发送请求
            progressBarWait.Visibility = Visibility.Visible;
            ConfirmButton.IsEnabled = false;
        }

        private void CancelButton_Click(object sender, RoutedEventArgs e)
        {
            UsernameBox.Text = "";
            PasswordBox.Password = "";
            SaveCheckBox.IsChecked = false;
            App.MyInfo.Id = UsernameBox.Text;
            App.MyInfo.Password = PasswordBox.Password;
            IsolatedStorageFile store = IsolatedStorageFile.GetUserStoreForApplication();
            StreamWriter fileWriter = null;
            fileWriter = new StreamWriter(new IsolatedStorageFileStream("userinfo.txt", FileMode.Create, store));
            fileWriter.WriteLine("UnChecked");
            fileWriter.Close();
        }

        private void HttpWebRequset_LogIn_Callback(IAsyncResult asynchronousResult)
        {
            try
            {
                //网络有错误将会在这里抛出异常
                string result = HttpUtil.ReadToEndWithParam(asynchronousResult);
                Debug.WriteLine(result);
                string ErrorInfo;
                //如果没有错误，LogInReport就是返回结果，ErrorInfo是空字符串
                //如果有错误，比如密码错误，这里LogInReport返回为空结果，ErrorInfo是错误信息
                UserInfo LogInReport = ParseUtil.ParseXml<UserInfo>(result, out ErrorInfo);
                if (LogInReport == null)
                {
                    this.Dispatcher.BeginInvoke(
                        () => {
                            progressBarWait.Visibility = Visibility.Collapsed;
                            ConfirmButton.IsEnabled = true;
                            MessageBox.Show(ErrorInfo);
                        }
                        );
                    return;
                }
                this.Dispatcher.BeginInvoke(
                    () => {
                        NavigationService.Navigate(new Uri("/BYRForum;component/MainPage.xaml", UriKind.Relative));
                        ConfirmButton.IsEnabled = true;
                        progressBarWait.Visibility = Visibility.Collapsed;
                    }
                    );
            }
            catch(Exception e)
            {
                Debug.WriteLine(e.Message);
                //这里处理异常，可以在界面上抛出messagebox
                this.Dispatcher.BeginInvoke(
                    () => {
                        progressBarWait.Visibility = Visibility.Collapsed;
                        ConfirmButton.IsEnabled = true;
                        MessageBox.Show("网络异常，请确认已经打开网络连接！");
                    }
                    );
            }
        }

        //密码输入完毕按回车自动登录
        private void PasswordBox_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.Key == Key.Enter)
            {
                if (UsernameBox.Text == "" || PasswordBox.Password == "")
                {
                    MessageBox.Show("密码或用户名不能为空！");
                    return;
                }
                App.MyInfo.Id = UsernameBox.Text;
                App.MyInfo.Password = PasswordBox.Password;
                Debug.WriteLine(App.MyInfo.Id + " " + App.MyInfo.Password);
                //保存用户名与密码
                IsolatedStorageFile store = IsolatedStorageFile.GetUserStoreForApplication();
                StreamWriter fileWriter = null;
                fileWriter = new StreamWriter(new IsolatedStorageFileStream("userinfo.txt", FileMode.Create, store));
                if (SaveCheckBox.IsChecked == true)
                {
                    fileWriter.WriteLine("Checked");
                    fileWriter.WriteLine(UsernameBox.Text);
                    fileWriter.WriteLine(PasswordBox.Password);
                }
                else
                {
                    fileWriter.WriteLine("UnChecked");
                }
                fileWriter.Close();

                String myRequestUrl = ByrApi.apiUrl + "/user/login" + ByrApi.Encode + ByrApi.appkey;
                RequestState state = new RequestState();
                HttpUtil.HttpGetWithParam(state, myRequestUrl, HttpWebRequset_LogIn_Callback);//发送请求
                progressBarWait.Visibility = Visibility.Visible;
                ConfirmButton.IsEnabled = false;
            }
        }

        protected override void OnBackKeyPress(System.ComponentModel.CancelEventArgs e)
        {
            if (MessageBox.Show("确定退出程序？", "退出", MessageBoxButton.OKCancel) == MessageBoxResult.Cancel)
            {
                e.Cancel = true;
                return;
            }
            while (NavigationService.BackStack.Any())
                NavigationService.RemoveBackEntry();
        }
    }
}